/**
  * 代理
  */
module game {
    export class ProxyMediator extends BaseMediator {
        public static NAME: string = "ProxyMediator";
        private gameType: string = "";
        public constructor(viewComponent: any = null) {
            super(ProxyMediator.NAME, viewComponent);
        }

        public listNotificationInterests(): Array<any> {
            return [
                PanelNotify.HALL.STAGE_RESIZE,
                PanelNotify.HALL.OPEN_PROXY,
                PanelNotify.HALL.CLOSE_PROXY
            ];
        }
        private panel: ProxyPanel;
        private erweima: egret.Sprite;
        public myProxyUrl = "";//我的推广链接
        public handleNotification(notification: puremvc.INotification): void {
            this.gameType = notification.getBody();
            switch (notification.getName()) {
                case PanelNotify.HALL.STAGE_RESIZE:
                    if (this.panel) {
                        this.panel.width = GameConfig.curWidth()
                        this.panel.height = GameConfig.curHeight()
                    }
                    break;
                case PanelNotify.HALL.OPEN_PROXY: {
                    this.panel = null;
                    this.panel = new ProxyPanel();
                    this.showUI(this.panel, 2, 1, true);
                    break;
                }
                case PanelNotify.HALL.CLOSE_PROXY: {
                    this.closePanel(0);
                    break;
                }
            }
        }

        /**
         * 初始化面板ui
         */
        public initUI(): void {
            this.panel.closeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeButtonClick, this);
            this.panel.wdtg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.tgmx.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.xjyh.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.tgjc.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.tgzb.addEventListener(egret.TouchEvent.TOUCH_TAP, this.typeClick, this);
            this.panel.lingqujiangli.addEventListener(egret.TouchEvent.TOUCH_TAP, this.lingqujiangliClick, this);
            this.panel.tiqujilu.addEventListener(egret.TouchEvent.TOUCH_TAP, this.tiqujilvClick, this);
            this.panel.youxibangzhu.addEventListener(egret.TouchEvent.TOUCH_TAP, this.proxyHelp, this);
            this.panel.weixinhaoyou.addEventListener(egret.TouchEvent.TOUCH_TAP, this.weChatClick, this);
            this.panel.back.addEventListener(egret.TouchEvent.TOUCH_TAP, this.backUpPage, this);
            this.panel.tgjc_copy.addEventListener(egret.TouchEvent.TOUCH_TAP, this.wxCopyClick, this);

        }

        /**
         * 初始化面板数据
         */
        public initData(): void {
            this.typeClick(null)
        }
        private closeButtonClick(event: egret.TouchEvent): void {
            SoundManage.startAnniuBtnLoad();
            this.closePanel(1);
        }

        //切换标签页
        private typeClick(event: egret.TouchEvent) {
            this.panel.wdtg.touchEnabled = true
            this.panel.tgmx.touchEnabled = true
            this.panel.xjyh.touchEnabled = true
            this.panel.tgjc.touchEnabled = true
            this.panel.tgzb.touchEnabled = true

            this.panel.wdtg.heidBG()
            this.panel.tgmx.heidBG()
            this.panel.xjyh.heidBG()
            this.panel.tgjc.heidBG()
            this.panel.tgzb.heidBG()

            this.panel.wdtg_vive.visible = false
            this.panel.tgmx_vive.visible = false
            this.panel.xjyh_vive.visible = false
            this.panel.tgjc_vive.visible = false
            this.panel.tgzb_vive.visible = false

            if (event == null || event.currentTarget == this.panel.wdtg) {
                this.panel.wdtg.touchEnabled = false
                this.panel.wdtg.showBG()
                this.panel.wdtg_vive.visible = true
                this.wdtgClick();
            } else if (event.currentTarget == this.panel.tgmx) {
                this.panel.tgmx.touchEnabled = false
                this.panel.tgmx.showBG()
                this.panel.tgmx_vive.visible = true
                this.tgmxClick();
            } else if (event.currentTarget == this.panel.xjyh) {
                this.panel.xjyh.touchEnabled = false
                this.panel.xjyh.showBG()
                this.panel.xjyh_vive.visible = true

                this.findUserId = GameVO.getVo().dwUserID
                this.userInfoArr = [];
                this.xjyhClick()
            } else if (event.currentTarget == this.panel.tgjc) {
                this.panel.tgjc.touchEnabled = false
                this.panel.tgjc.showBG()
                this.panel.tgjc_vive.visible = true
                this.tgjcClick();
            } else if (event.currentTarget == this.panel.tgzb) {
                this.panel.tgzb.touchEnabled = false
                this.panel.tgzb.showBG()
                this.panel.tgzb_vive.visible = true
                this.tgzbClick();
            }
        }
        //查询我的推广
        private wdtgClick() {
            var time = Global.getCurrTimeLong()
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/agentChoushui/myspread/" + GameVO.getVo().dwUserID + "?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.showWdtgView(obj);
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //显示我的推广
        private showWdtgView(obj: Object) {
            if (this.erweima && this.panel.wdtg_vive.contains(this.erweima)) {
                this.panel.wdtg_vive.removeChild(this.erweima)
                this.erweima = null;
            }
            this.panel.choushui.text = obj["choushui"]
            this.panel.childCnt.text = obj["childCnt"]
            this.panel.otherCnt.text = obj["otherCnt"]
            this.panel.sonChouShui.text = obj["sonChouShui"]
            this.panel.otherChouShui.text = obj["otherChouShui"]
            this.panel.AgentHistoryReward.text = obj["AgentHistoryReward"]
            this.panel.AgentAvailableReward.text = obj["AgentAvailableReward"]
            this.myProxyUrl = InstructionsEnum.IP_API + obj["downloadUrl"]
            this.erweima = qr.QRCode.create(this.myProxyUrl)
            this.erweima.x = this.panel.erweima.x;
            this.erweima.y = this.panel.erweima.y;
            this.panel.wdtg_vive.addChild(this.erweima);
            if (obj["AgentAvailableReward"] == 0 || obj["AgentAvailableReward"] == null) {
                this.panel.lingqujiangli.enabled = false;
            } else {
                this.panel.lingqujiangli.enabled = true;
            }
        }
        //查询推广明细
        private tgmxClick() {
            var time = Math.floor(Global.getCurrTimeLong() / 1000)//这个逼接口时间是以秒做单位
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/agentChoushui/DetailReport/" + GameVO.getVo().dwUserID + "?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.showTgmxView(obj)
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //显示推广明细
        private showTgmxView(obj: Object) {
            this.panel.tgmx_dataGroup.removeChildren()
            var datas: Array<any> = obj["datas"]
            if (datas.length == 0) {
                this.panel.tgmx_wushuju.visible = true
            } else {
                this.panel.tgmx_wushuju.visible = false
            }
            for (var i = 0; i < datas.length; i++) {
                var data = new components.proxyChoushui(datas[i])
                this.panel.tgmx_dataGroup.addChild(data);
            }
        }

        private userInfoArr: Array<Array<any>> = [];//下级用户列表
        private findUserId: number = null;//要查询下级用的的玩家ID
        //查询下级用户
        private xjyhClick() {
            var time = Global.getCurrTimeLong()
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/agentChoushui/AgentTeamInfo?userid=" + this.findUserId + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        var data: Array<any> = obj["datas"];
                        this.userInfoArr.push(data)
                        this.showXjyhView()
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send("id=" + this.findUserId);

        }
        //点击儿子用户查询孙子用户
        private userInfoClick(eve: egret.TouchEvent) {
            var userID = eve.currentTarget.name;
            this.findUserId = userID;
            this.xjyhClick();
        }
        //孙子用户返回儿子用户
        private backUpPage() {
            if (this.userInfoArr.length != 0) {
                this.userInfoArr.splice(this.userInfoArr.length - 1);
            }
            this.showXjyhView();
        }
        //显示下级用户
        private showXjyhView() {
            this.panel.back.visible = false;
            this.panel.xjyh_dataGroup.removeChildren();

            if (this.userInfoArr.length == 0) {
                this.panel.tgmx_wushuju.visible = true
            } else {
                this.panel.tgmx_wushuju.visible = false
            }
            if (this.userInfoArr.length != 0) {
                if (this.userInfoArr.length > 1) {
                    this.panel.back.visible = true;
                }
                var data: Array<any> = this.userInfoArr[this.userInfoArr.length - 1];
                if (data.length == 0) {
                    this.panel.tgmx_wushuju.visible = true
                } else {
                    this.panel.tgmx_wushuju.visible = false
                }
                var y = 0;
                for (var i = 0; i < data.length; i++) {
                    var group = new eui.Group();
                    var time: string = data[i]["RegTime"]
                    time = time.replace(" ", "\r")
                    var bg = new eui.Image("proxy_hd");
                    var RegTime = new eui.Label(time + "")
                    var Account = new eui.Label(data[i]["Account"] + "")
                    var Revenue = new eui.Label(data[i]["Revenue"] + "")
                    var UserCnt = new eui.Label(data[i]["UserCnt"] + "")
                    var TeamRevenue = new eui.Label(data[i]["TeamRevenue"] + "")

                    RegTime.x = 10
                    RegTime.y = 6
                    RegTime.width = 150
                    RegTime.textAlign = "center"
                    RegTime.size = 20
                    RegTime.textColor = 0xF7DEBB

                    Account.x = 150
                    Account.y = 10
                    Account.width = 200
                    Account.textAlign = "center"
                    Account.size = 26
                    Account.textColor = 0x6BA8CE

                    Revenue.x = 360
                    Revenue.y = 10
                    Revenue.width = 100
                    Revenue.textAlign = "center"
                    Revenue.size = 26
                    Revenue.textColor = 0x6BA8CE

                    UserCnt.x = 535
                    UserCnt.y = 10
                    UserCnt.width = 100
                    UserCnt.textAlign = "center"
                    UserCnt.size = 26
                    UserCnt.textColor = 0x6BA8CE

                    TeamRevenue.x = 745
                    TeamRevenue.y = 10
                    TeamRevenue.width = 100
                    TeamRevenue.textAlign = "center"
                    TeamRevenue.size = 26
                    TeamRevenue.textColor = 0x6BA8CE
                    group.y = y;
                    group.addChild(bg)
                    group.addChild(RegTime)
                    group.addChild(Account)
                    group.addChild(Revenue)
                    group.addChild(UserCnt)
                    group.addChild(TeamRevenue)
                    this.panel.xjyh_dataGroup.addChild(group)
                    y += 50
                    if (data[i]["UserCnt"] != 0) {
                        group.name = data[i]["UserId"]
                        group.addEventListener(egret.TouchEvent.TOUCH_TAP, this.userInfoClick, this)
                    }
                }
            }
        }

        //查询推广教程
        private tgjcClick() {
            var time = Math.floor(Global.getCurrTimeLong() / 1000)//这个逼接口时间是以秒做单位
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/GameWebApplication/GetAgentUrl.ashx/" + GameVO.getVo().dwUserID + "?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.showTgjcView(obj)
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //显示推广教程
        private showTgjcView(obj: Object) {
            var WxList: Array<string> = obj["WxList"];
            if (WxList.length != 0) {
                this.panel.wxNumber.text = "财富微信:" + WxList[0]
                this.panel.wxNumber.name = WxList[0]
                this.panel.tgjc_copy.visible = true;
            } else {
                this.panel.wxNumber.text = "暂无数据"
                this.panel.tgjc_copy.visible = false
            }
        }
        //查询推广周榜
        private tgzbClick() {
            var time = Global.getCurrTimeLong()
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/agentChoushui/Leaderboard?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        this.showTgzbView(obj)
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //显示推广周榜
        private showTgzbView(obj: Object) {
            this.panel.tgzb_dataGroup.removeChildren();
            var y = 0;
            var data: Array<any> = obj["data"];
            for (var i = 0; i < data.length; i++) {
                var bg = new eui.Image("proxy_hd");
                bg.y = y
                this.panel.tgzb_dataGroup.addChild(bg)
                var bg2 = new eui.Image("proxy_jinbi");
                bg2.x = 707
                bg2.y = y + 8
                this.panel.tgzb_dataGroup.addChild(bg2)

                var num = i + 1;
                var xuhao = new eui.BitmapLabel();
                xuhao.x = 45
                xuhao.y = y + 10
                xuhao.width = 60
                xuhao.font = "proxy_top_fnt"
                xuhao.textAlign = "center"
                if (num == 1) {
                    xuhao.text = "a"
                } else if (num == 2) {
                    xuhao.text = "b"
                } else if (num == 3) {
                    xuhao.text = "c"
                } else {
                    xuhao.text = num + "";
                }

                var name = new eui.Label(data[i]["name"] + "")
                name.x = 340
                name.y = y + 10
                name.size = 26
                name.textColor = 0x6BA8CE;
                name.width = 150
                name.textAlign = "center"

                var choushui = new eui.Label(data[i]["choushui"] + "")
                choushui.x = 750
                choushui.y = y + 10
                choushui.size = 26
                choushui.textColor = 0xE5D379;

                this.panel.tgzb_dataGroup.addChild(xuhao)
                this.panel.tgzb_dataGroup.addChild(name)
                this.panel.tgzb_dataGroup.addChild(choushui)
                y += 50
            }
        }
        //点击申请提取奖励
        private lingqujiangliClick() {
            var time = Math.floor(Global.getCurrTimeLong() / 1000)//这个逼接口时间是以秒做单位
            var signature = Global.getSynLoginKey(time)
            signature = signature.toUpperCase()
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/agentChoushui/apply/" + GameVO.getVo().dwUserID + "?userid=" + GameVO.getVo().dwUserID + "&signature=" + signature + "&time=" + time, egret.HttpMethod.POST);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                try {
                    var request = <egret.HttpRequest>event.currentTarget;
                    var obj = JSON.parse(request.response)
                    if (obj.code == 0) {
                        Global.tipShow("申请成功，请等待审核!")
                        this.wdtgClick()
                    } else {
                        Global.tipShow(obj.msg)
                    }
                } catch (err) {
                    EffectUtils.textFadeAway("数据包异常，无法解析!")
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            EffectUtils.showWaritPanel()
            request.send();
        }
        //点击提取记录
        private tiqujilvClick() {
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_TIQUJILU);
        }
        //点击游戏帮助
        private proxyHelp() {
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_PROXY_HELP);
        }
        //点击微信分享
        private weChatClick() {
            // window.open(this.myProxyUrl)
            copyText(this.myProxyUrl)
            Global.tipShow("您的推广链接已复制到粘贴板，请发送给您的好友!")
        }
        private wxCopyClick() {
            copyText(this.panel.wxNumber.name)
            Global.tipShow("推广指导员的微信号已复制到粘贴板，请通过微信添加好友!")
        }
    }
}
